package com.haohan.cloud.framework.utils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Vector;
import java.util.zip.CRC32;

public class ConsistentHash<T> {

	private int num = 1;

	private final Vector<T> circle = new Vector<T>();

	public static void main(String args[]) {
		List<String> list = new ArrayList<String>();
		String node1 = "node1";
		String node2 = "node2";
		list.add(node1);
		list.add(node2);
		ConsistentHash<String> ch = new ConsistentHash<String>(list);
		// System.out.println((int) (Math.abs(ch.hashcode(2+"")) %
		// list.size()));
		System.out.println(ch.get(2));
	}

	public ConsistentHash(Collection<T> nodes) {
		num = nodes.size();
		num = num > 0 ? num : 1;
		circle.addAll(nodes);
	}

	public static long hashcode(String input) {
		CRC32 crc32 = new CRC32();
		crc32.update(input.getBytes());
		return crc32.getValue();
	}

	public T get(Object key) {
		if (circle.isEmpty()) {
			return null;
		}
		return circle.get((int) (Math.abs(hashcode(key.toString())) % num));
	}

}
